package com.gooth.onway;

import android.util.Log;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;

public class LocationUpdater implements BDLocationListener
{
	public String server_uri=null;

	public void setServerUri(String uri)
	{
		server_uri = uri;
	}

	@Override
	public void onReceiveLocation(BDLocation loc) {
		updateToServer(loc);
		Log.d("OnWay","Got location,"
				+" lat="+String.valueOf(loc.getLatitude())
				+" lng="+String.valueOf(loc.getLongitude())
		);
	}

	@Override
	public void onReceivePoi(BDLocation loc) {
		updateToServer(loc);
		StringBuffer sb = new StringBuffer(256);
		sb.append("Got Location:");
		sb.append("Lat=");
		sb.append(loc.getLatitude());
		sb.append("Lng=");
		sb.append(loc.getLongitude());
		Log.d("OnWay", sb.toString());
	}


	public void updateToServer(final BDLocation location) {
		new Thread(){
			public void run(){
				HttpPost request = new HttpPost(server_uri);

				String lat = String.valueOf(location.getLatitude());
				String lng = String.valueOf(location.getLongitude());

				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("lat",lat));
				params.add(new BasicNameValuePair("lng",lng));

				try {
					request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
					HttpResponse response = new DefaultHttpClient().execute(request);
					if(response.getStatusLine().getStatusCode()==200) {
						String reply = EntityUtils.toString(response.getEntity());
						Log.d("OnWay", "Server response :" + reply);
					}
				} catch (Exception e) {
					e.printStackTrace();
					Log.e("OnWay","Error happened while visit "+server_uri);
				}
			}
		}.start();
	}
}
